package com.hebang.stcommunityapp.tools;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;

/**
 * 本地 图片/文件/音频等等 获取的 uri 转换成为本地的 path 路径
 * @author zjw
 */
public class UriChange {
    /**
     * Try to return the absolute file path from the given Uri
     */
    public String getRealFilePath(Context context, Uri uri) {
        Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
        String path = null;
        if (cursor != null) {
            cursor.moveToFirst();
            String document_id = cursor.getString(0);
            document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
            cursor.close();

            cursor = context.getContentResolver().query(
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
            if (cursor != null) {
                cursor.moveToFirst();
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                cursor.close();
            }
        }
        return path;
    }

    /**
     * 获取上传文件图片的基地址
     */
    public String getSDPath(Uri uri, Activity activity) {
        String img_path = "";
        //如果是华为手机，调用上面给出的方法，即可得到正确的图片途径
//        if (RomUtil.isEmui()) {
//            img_path = getRealFilePath(activity, uri);
//        } else {
            String[] proj = {MediaStore.Images.Media.DATA};
            Cursor actualimagecursor = activity.managedQuery(uri, proj, null, null, null);
            int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            actualimagecursor.moveToFirst();
            img_path = actualimagecursor.getString(actual_image_column_index);
//        }
        return img_path;
    }
}